package com.redis.demo.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author zqf
 * @Date 2022/11/2 16:18
 * @Description: redis实现排行榜
 */


@RestController("/sort")
@Api(tags = "redis实现排行榜功能")
public class RankingListController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static final String SCORE_RANK = "score_rank1";

    /**
     * 批量新增
     */
    @GetMapping("addZset")
    @ApiOperation("批量添加元素到set")
    public void batchAdd() {
        for (int i = 0; i < 100; i++) {
            redisTemplate.opsForZSet().add(SCORE_RANK,"user"+i,i);
        }
        System.out.println("添加成功");
    }

    /**
     * 获取排行列表
     */

    @GetMapping("getZset")
    @ApiOperation("获取指定位置的旁行，例如前10：1-10")
    public Set list(@RequestParam("start") Integer start, @RequestParam("end")Integer end) {

        Set<Object> range = redisTemplate.opsForZSet().reverseRange(SCORE_RANK, start, end);
        System.out.println("获取到的排行列表:" + JSON.toJSONString(range));
        Set<ZSetOperations.TypedTuple<Object>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(SCORE_RANK, start, end);
        System.out.println("获取到的排行和分数列表:" + JSON.toJSONString(rangeWithScores));
        return range;
    }

}
